package com.aletto.demo_android_web3j;

import android.util.Log;

import com.aletto.demo_android_web3j.utils.ERC20Utils;

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.RemoteFunctionCall;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/** 生成命令行
 java -jar web3j-cli.jar generate solidity \
 -a /Users/mondo/Downloads/web3j/market.abi \
 -b /Users/mondo/Downloads/web3j/market.bin \
 -o /Users/mondo/Downloads/web3j//java \
 -p com.yourcompany.yourproject
 */
public class ExampleTest {

    private static final byte chainId = BigInteger.valueOf(97).byteValue();

    private static final String TAG = "ExampleTest";

    private static final Web3j web3j = Web3j.build(
            new HttpService(
                    "https://endpoints.omniatech.io/v1/bsc/testnet/public",
                    new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .addNetworkInterceptor(
                                    new HttpLoggingInterceptor()
                                            .setLevel(HttpLoggingInterceptor.Level.BODY)
                            )
                            .build()
            )
    );

    public static void init() throws Exception {
        TransactionManager transactionManager = new RawTransactionManager(
                web3j,
//                Credentials.create(C.ACCOUNT.BUYER.privateKey),
                Credentials.create("0xa4565b38a46bd1312cb208655e1fa92e9056411e2180693678d3cb988f14c9c6"),
                chainId
        );

        Market load = Market.load(C.MARKET_CONTRACT_ADDRESS, web3j, transactionManager, new DefaultGasProvider());

        RemoteFunctionCall<TransactionReceipt> call = load.buy(
                new BigInteger("10010"),
                new BigInteger("10"),
                new BigInteger("1"),
                new BigInteger("1"),
                C.ACCOUNT.SELLER.address
        );

        call.send();
    }


    public static void approve(Consumer<String> consumer) {

        try {

            EthSendTransaction ethSendTransaction = ERC20Utils.approve(
                    web3j,
                    BigInteger.valueOf(97).byteValue(),
                    Credentials.create(C.ACCOUNT.BUYER.privateKey),
                    C.MARKET_CONTRACT_ADDRESS,
                    C.USDT_CONTRACT_ADDRESS,
                    Convert.toWei("2000", Convert.Unit.ETHER).toBigInteger()
            );

            if (!ethSendTransaction.hasError()) {
                consumer.accept("Approve成功, 交易哈希: " + ethSendTransaction.getTransactionHash());

            } else {
                consumer.accept("Approve失败: " + ethSendTransaction.getError().getMessage());
            }

        } catch (Exception e) {
            e.printStackTrace();
            consumer.accept("[ERROR]: " + e.getLocalizedMessage());
        }
    }

    public static void allowance(Consumer<String> consumer) {

        try {

            init();

            //BigDecimal allowance = ERC20Utils.allowance(web3j, C.USDT_CONTRACT_ADDRESS, C.ACCOUNT.BUYER.address, C.MARKET_CONTRACT_ADDRESS);
            //consumer.accept("授权额度: " + allowance);

        } catch (Exception e) {

            e.getLocalizedMessage();
            consumer.accept(e.getLocalizedMessage());
        }

    }

    public static void balance_1(Consumer<String> consumer) {
        try {
            // -------------------- 查询USDT余额 --------------------
            BigDecimal balance = ERC20Utils.balance(
                    web3j,
//                    BigInteger.valueOf(97).byteValue(),
                    Credentials.create(C.ACCOUNT.BUYER.privateKey),
                    C.USDT_CONTRACT_ADDRESS
            );
            consumer.accept("Balance: " + balance + " USDT");

        } catch (Exception e) {
            e.printStackTrace();
            consumer.accept(e.getLocalizedMessage());
        }
    }

    public static void balance_2(Consumer<String> consumer) {
        try {
            // -------------------- 查询BNB余额 --------------------
            String walletAddress = C.ACCOUNT.BUYER.address; // 目标地址，这里需要替换为你想要查询余额的地址
            EthGetBalance ethGetBalance = web3j.ethGetBalance(walletAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
            if (ethGetBalance.hasError()) {
                Log.i(TAG, "Balance: " + ethGetBalance.getError().getMessage());
                return;
            }

            // 将Wei转换为BNB
            BigInteger balanceWei = ethGetBalance.getBalance();
            BigDecimal balance = Convert.fromWei(balanceWei.toString(), Convert.Unit.ETHER);
            consumer.accept("Balance: " + balance.toPlainString() + " BNB");

        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }


}
